package com.masterrabbit.gmh.controller;

import com.masterrabbit.common.core.domain.R;
import com.masterrabbit.gmh.domain.Images;
import com.masterrabbit.gmh.domain.RepairRecords;
import com.masterrabbit.gmh.service.ImagesService;
import com.masterrabbit.gmh.service.RepairRecordsService;
import com.masterrabbit.sn.util.OSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/repairRecord")
public class RepairRecordController {

    @Autowired
    private RepairRecordsService repairRecordsService;
@Autowired
private ImagesService imagesService;


    public String getUUID() {
        String uuidStr = UUID.randomUUID().toString();
        // 去除连字符（生成32位字符串）
        String compactUUID = uuidStr.replace("-", "");
        System.out.println("无连字符UUID: " + compactUUID);
        return compactUUID;
    }


    @PostMapping("/add")
    public boolean addRepairRecord(@RequestBody RepairRecords repairRecords) {


        String uuid= getUUID();
        System.out.println(uuid);
        repairRecords.setRepairNumber(uuid);


        return  repairRecordsService.save(repairRecords);
    }


    @PostMapping("/upload")
    public R<List<Images>> uploadImages(@RequestParam("files") MultipartFile[] files, @RequestParam(value = "parentId", required = false) Long parentId) {
        List<Images> imageList = new ArrayList<>();
        try {
            // 逐个处理上传的图片
            for (MultipartFile file : files) {
                String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                InputStream inputStream = file.getInputStream();
                String imageUrl = OSSUtil.upload(fileName, inputStream);
                Images images = new Images();
                images.setImageUrl(imageUrl);
                if (parentId != null) {
                    images.setParentId(Math.toIntExact(parentId));  // 设置 parentId
                }
                imageList.add(images);  // 将图片加入返回列表
            }
            // 批量插入所有图片
            if (!imageList.isEmpty()) {
                imagesService.saveBatch(imageList);  // 批量插入
            }
            System.out.println(imageList);
            return R.ok(imageList);  // 返回上传的图片信息
        } catch (IOException e) {
            return R.fail("图片上传失败: " + e.getMessage());
        }
    }


}
